<?php

namespace app\controllers;

use app\tools\Tool;
use app\models\User;
use app\models\UserLogin;
use app\models\Identity;
use Yii;
use app\tools\Re;
use app\filters\auth\HttpBearerAuth;
use yii\rest\Controller;
use yii\web\Response;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
date_default_timezone_set("PRC");

class BaseController extends Controller
{
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['corsFilter'] = [
            'class' => 'yii\filters\Cors',
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['*'],
                'Access-Control-Allow-Origin' => ['*'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age' => 86400,
                'Access-Control-Expose-Headers' => [],
            ],
        ];
        return $behaviors;
    }

    public function init()
    {
        parent::init();
        Yii::$app->user->enableSession = false;
    }

    /**
     * 获取企业工商信息
     */
    public function getBusinessInfo($company_name){
        $appcode = '4c7afad5f8564494b7b513f1ecd7945d';
        $url = "https://bankpros.market.alicloudapi.com/comdata";
        $method = "POST";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
        $querys = "";
        $bodys = "com=".$company_name;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $result_data = json_decode(curl_exec($curl));
        return $result_data;
    }

    //base64码转图片
    public function base64ToImg($img_content, $type) {
      $img_path = 'article_img_txjj_'.$type.'.png';
      file_put_contents($img_path, $img_content);
      $res = $this->putFileToQiniu($img_path);
      return $res;
    }

    //本地图片上传七牛
    public function putFileToQiniu($filePath) {
      //$filePath = str_replace('//', '', $filePath);
      $qiniu = Yii::$app->params['qiniu'];
      $bucket = $qiniu['bucket'];
      $url    = $qiniu['url'];
      $policy = [
          'saveKey'    => '$(etag)$(ext)',
          'returnBody' => '{"key":$(key),"domain":"' . $url . '","size":$(fsize),"w": $(imageInfo.width),"h":$(imageInfo.height),"hash":$(etag)}'
      ];
      $auth = new Auth($qiniu['access_key'], $qiniu['secret_key']);
      $token = $auth->uploadToken($bucket, null, 3600, $policy);
      $uploadMgr = new UploadManager();
      list($res, $err) = $uploadMgr->putFile($token, null, $filePath);
      if($err == null) {
        unlink($filePath);
        return $res;
      }
    }

    //抓取远程图片上传七牛
    public function fetchFileToQiniu($filePath) {
      //$filePath = str_replace('//', '', $filePath);
      $qiniu = Yii::$app->params['qiniu'];
      $auth = new Auth($qiniu['access_key'], $qiniu['secret_key']);
      $bucketMgr = new BucketManager($auth);
      list($res, $err) = $bucketMgr->fetch($filePath, $qiniu['bucket'], null);
      if($err == null) {
        return $res;
      }
    }

    //获取客户端ip信息
    public function getIpAreaName() {
        $env = Yii::$app->params['env'];
        if ($env == 'dev') {//本地环境
            $ip = file_get_contents('http://pv.sohu.com/cityjson?ie=utf-8');
            preg_match('/{.+}/i', $ip, $m);
            $array = json_decode($m[0]);
            $ip = $array->cip;
        } else {
            if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
                $cip = $_SERVER["HTTP_CLIENT_IP"];
            } else if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
                $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (!empty($_SERVER["REMOTE_ADDR"])) {
                $cip = $_SERVER["REMOTE_ADDR"];
            } else {
                $cip = '';
            }
            preg_match("/[\d\.]{7,15}/", $cip, $cips);
            $ip = isset($cips[0]) ? $cips[0] : 'unknown';
            unset($cips);
        }
        $url = "http://api.map.baidu.com/location/ip?ip=".$ip."&ak=pDdi7AY3999O01bmMTRMViB6";
        @file_get_contents($url);
        $http_code = $http_response_header[0];
        if(strpos($http_code,'200 OK') !== false){
            $result = file_get_contents($url); //调用接口获取信息
            $result = mb_convert_encoding($result, "utf-8", "gb2312"); // 编码转换，否则乱码
            $result = json_decode($result,true);
            $ip_area_name = $result['content']['address_detail']['province'] . '·' . $result['content']['address_detail']['city'];
            return $ip_area_name;
        }
    }
}
